<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态线程池监控与配置</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>

    <!-- Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        accent: '#FF7D00',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        info: '#86909C',
                        light: '#F2F3F5',
                        dark: '#1D2129',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 4px 12px rgba(0, 0, 0, 0.08)',
                        'card-hover': '0 8px 24px rgba(0, 0, 0, 0.12)',
                    }
                },
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-transition {
                transition: all 0.3s ease;
            }
            .progress-bar {
                transition: width 0.5s ease;
            }
            .hover-scale {
                transition: transform 0.2s ease;
            }
            .hover-scale:hover {
                transform: scale(1.02);
            }
        }
    </style>

    <style>
        /* 自定义滚动条 */
        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }
        ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }

        /* 进度条样式 */
        .progress {
            height: 10px;
            background-color: #e9ecef;
            border-radius: 5px;
            overflow: hidden;
        }
        .progress-bar {
            height: 100%;
            background-color: #165DFF;
        }

        /* 加载动画 */
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        .animate-pulse {
            animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }
    </style>
</head>
<body class="bg-gray-50 font-inter text-dark min-h-screen">
<div class="container mx-auto px-4 py-6 max-w-7xl">
    <!-- Toast 提示容器 -->
    <div id="toast-container" class="fixed bottom-4 right-4 space-y-2 z-50"></div>
    <!-- 页面标题 -->
    <header class="mb-8 text-center">
        <h1 class="text-[clamp(1.8rem,3vw,2.5rem)] font-bold text-dark flex items-center justify-center">
            <i class="fa fa-tachometer mr-3 text-primary"></i>
            动态线程池监控与配置
        </h1>
        <p class="text-gray-500 mt-2">实时监控线程池状态并动态调整配置参数</p>
    </header>

    <!-- 主要内容区域 -->
    <main class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 gap-6">
        <!-- 线程池列表卡片 -->
        <div class="bg-white rounded-xl shadow-card p-6 card-transition hover:shadow-card-hover">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-xl font-semibold flex items-center">
                    <i class="fa fa-list-ul mr-2 text-primary"></i>
                    线程池列表
                </h2>
                <span id="poolCount" class="bg-primary/10 text-primary px-3 py-1 rounded-full text-sm">3 个线程池</span>
            </div>
            <ul id="poolList" class="space-y-2 overflow-y-auto max-h-[calc(100vh-300px)]">
                <!-- 线程池列表将通过JavaScript动态生成 -->
            </ul>
        </div>

        <!-- 线程池详情卡片 -->
        <div class="bg-white rounded-xl shadow-card p-6 card-transition hover:shadow-card-hover">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-xl font-semibold flex items-center">
                    <i class="fa fa-info-circle mr-2 text-primary"></i>
                    线程池详情 -
                    <span id="selectedPoolName" class="text-primary font-medium">pool-1</span>
                </h2>
<!--                <button id="refreshDetails" class="text-gray-400 hover:text-primary transition-colors">-->
<!--                    <i class="fa fa-refresh"></i>-->
<!--                </button>-->
            </div>
            <div id="poolDetails" class="space-y-4">
                <!-- 线程池详情将通过JavaScript动态生成 -->
            </div>
        </div>

        <!-- 线程池配置卡片 -->
        <div class="bg-white rounded-xl shadow-card p-6 card-transition hover:shadow-card-hover">
            <h2 class="text-xl font-semibold mb-4 flex items-center">
                <i class="fa fa-cog mr-2 text-primary"></i>
                线程池配置
            </h2>
            <form id="configForm" class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label for="poolName" class="block text-sm font-medium text-gray-700 mb-1">线程池名称</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fa fa-tag text-gray-400"></i>
                            </div>
                            <input type="text" id="poolName" name="poolName"
                                   class="pl-10 block w-full rounded-lg border border-gray-300 py-2.5 bg-gray-50 text-gray-900 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all"
                                   placeholder="输入线程池名称" value="pool-1" required>
                        </div>
                    </div>

                    <div>
                        <label for="corePoolSize" class="block text-sm font-medium text-gray-700 mb-1">核心线程数</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fa fa-users text-gray-400"></i>
                            </div>
                            <input type="number" id="corePoolSize" name="corePoolSize"
                                   class="pl-10 block w-full rounded-lg border border-gray-300 py-2.5 bg-gray-50 text-gray-900 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all"
                                   placeholder="核心线程数" value="5" min="1" required>
                        </div>
                    </div>

                    <div>
                        <label for="maxPoolSize" class="block text-sm font-medium text-gray-700 mb-1">最大线程数</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fa fa-users text-gray-400"></i>
                            </div>
                            <input type="number" id="maxPoolSize" name="maxPoolSize"
                                   class="pl-10 block w-full rounded-lg border border-gray-300 py-2.5 bg-gray-50 text-gray-900 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all"
                                   placeholder="最大线程数" value="10" min="1" required>
                        </div>
                    </div>

                    <div>
                        <label for="keepAliveTime" class="block text-sm font-medium text-gray-700 mb-1">存活时间(秒)</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fa fa-clock-o text-gray-400"></i>
                            </div>
                            <input type="number" id="keepAliveTime" name="keepAliveTime"
                                   class="pl-10 block w-full rounded-lg border border-gray-300 py-2.5 bg-gray-50 text-gray-900 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all"
                                   placeholder="存活时间" value="60" min="1" required>
                        </div>
                    </div>

                    <div>
                        <label for="queueCapacity" class="block text-sm font-medium text-gray-700 mb-1">队列容量</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fa fa-list-alt text-gray-400"></i>
                            </div>
                            <input type="number" id="queueCapacity" name="queueCapacity"
                                   class="pl-10 block w-full rounded-lg border border-gray-300 py-2.5 bg-gray-50 text-gray-900 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all"
                                   placeholder="队列容量" value="100" min="1" required>
                        </div>
                    </div>

                    <div>
                        <label for="rejectEnum" class="block text-sm font-medium text-gray-700 mb-1">拒绝策略</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fa fa-ban text-gray-400"></i>
                            </div>
                            <select id="rejectEnum" name="rejectEnum"
                                    class="pl-10 block w-full rounded-lg border border-gray-300 py-2.5 bg-gray-50 text-gray-900 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all appearance-none pr-8">
                                <option value="CallerRunsPolicy">CallerRunsPolicy</option>
                                <option value="AbortPolicy">AbortPolicy</option>
                                <option value="DiscardPolicy">DiscardPolicy</option>
                                <option value="DiscardOldestPolicy">DiscardOldestPolicy</option>
                            </select>
                            <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-400">
                                <i class="fa fa-chevron-down text-xs"></i>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="flex justify-end pt-2">
                    <button type="button" id="addPoolBtn" class="group relative inline-flex items-center justify-center px-5 py-3 overflow-hidden font-medium bg-secondary text-white rounded-lg hover:bg-secondary/90 focus:outline-none focus:ring-2 focus:ring-secondary/30 transition-all mr-2">
                        <span class="absolute inset-0 w-full h-full bg-white/25 rounded-full opacity-0 group-hover:opacity-100 transition-all duration-500 scale-125"></span>
                        <i class="fa fa-plus mr-2"></i>
                        创建新配置
                    </button>
                    <button type="submit" class="group relative inline-flex items-center justify-center px-5 py-3 overflow-hidden font-medium bg-primary text-white rounded-lg hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-primary/30 transition-all">
                        <span class="absolute inset-0 w-full h-full bg-white/25 rounded-full opacity-0 group-hover:opacity-100 transition-all duration-500 scale-125"></span>
                        <i class="fa fa-save mr-2"></i>
                        更新配置
                    </button>
                </div>
            </form>
        </div>

        <!-- 图表卡片 -->
        <div class="bg-white rounded-xl shadow-card p-6 card-transition hover:shadow-card-hover">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-xl font-semibold flex items-center">
                    <i class="fa fa-line-chart mr-2 text-primary"></i>
                    线程池状态监控
                </h2>
<!--                <div class="flex space-x-2">-->
<!--                    <button id="chartRefresh" class="text-gray-400 hover:text-primary transition-colors">-->
<!--                        <i class="fa fa-refresh"></i>-->
<!--                    </button>-->
<!--                    <div class="relative">-->
<!--                        <button id="chartTimeRange" class="text-sm text-gray-600 hover:text-primary transition-colors flex items-center">-->
<!--                            最近1小时 <i class="fa fa-chevron-down ml-1 text-xs"></i>-->
<!--                        </button>-->
<!--                        <div id="timeRangeDropdown" class="hidden absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg py-1 z-10">-->
<!--                            <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">最近30分钟</a>-->
<!--                            <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">最近1小时</a>-->
<!--                            <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">最近6小时</a>-->
<!--                            <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">最近24小时</a>-->
<!--                        </div>-->
<!--                    </div>-->
<!--                </div>-->
            </div>
            <div id="chart" class="w-full h-[350px]"></div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="mt-12 text-center text-gray-500 text-sm">
        <p>© 2025 动态线程池监控系统 | 实时监控与配置中心</p>
    </footer>
</div>

    <script>
        // 获取DOM元素
        const addPoolBtn = document.getElementById('addPoolBtn');

        // 新增线程池按钮点击事件
        addPoolBtn.addEventListener('click', function() {
            // 清空表单并设置默认值
            configForm.reset();
            document.getElementById('corePoolSize').value = '5';
            document.getElementById('maxPoolSize').value = '10';
            document.getElementById('keepAliveTime').value = '60';
            document.getElementById('queueCapacity').value = '500';
            rejectEnumSelect.value = 'CallerRunsPolicy';
            showToast('请输入新线程池参数后更新配置,部分默认可修改', 'success');
        });

        // 获取DOM元素
        const poolList = document.getElementById('poolList');
        const selectedPoolName = document.getElementById('selectedPoolName');
        const poolDetails = document.getElementById('poolDetails');
        const configForm = document.getElementById('configForm');
        const chartDom = document.getElementById('chart');
        const rejectEnumSelect = document.getElementById('rejectEnum');
        // 线程池个数
        const poolCountDoC = document.getElementById("poolCount");
        let chart = echarts.init(chartDom);
        let currentSelectedPool = null;
        // 显示Toast消息
        function showToast(message, type = 'success') {
            const container = document.getElementById('toast-container');
            const toast = document.createElement('div');
            toast.className = `
                px-4 py-3 rounded-lg shadow-lg text-white
                ${type === 'success' ? 'bg-success' : 'bg-danger'}
                opacity-0 transform translate-y-4
            `;
            toast.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
            toast.textContent = message;

            container.appendChild(toast);
            void toast.offsetWidth; // 强制重排

            // 显示动画
            setTimeout(() => {
                toast.style.opacity = 1;
                toast.style.transform = 'translateY(0)';
            }, 10);

            // 隐藏动画
            setTimeout(() => {
                toast.style.opacity = 0;
                toast.style.transform = 'translateY(-1rem)';
                toast.addEventListener('transitionend', () => {
                    toast.remove();
                }, { once: true });
            }, 3000);
        }


        // 获取拒绝策略枚举
        function getRejectEnums() {
            fetch('/lancer-thread-pool/monitor/getRejectEnum')
                .then(response => response.json())
                .then(data => {
                    if (data.status === 1) { // 使用正确的状态码1表示成功
                        rejectEnumSelect.innerHTML = '';
                        Object.entries(data.resultData).forEach(([key, value]) => {
                            const option = document.createElement('option');
                            option.value = key;
                            option.textContent = value;
                            rejectEnumSelect.appendChild(option);
                        });
                    }
                });
        }
        
        // 选择特定线程池
        function selectPool(poolName) {
            currentSelectedPool = poolName;
            selectedPoolName.textContent = poolName;
            getThreadPoolDetails(poolName);
        }
        
        // 获取所有线程池列表
        function getThreadPoolList() {
            fetch('/lancer-thread-pool/monitor/queryList')
                .then(response => response.json())
                .then(data => {
                    if (data.status === 1) { // 使用正确的状态码1表示成功
                        poolList.innerHTML = '';
                        data.resultData.forEach(pool => {
                            const li = document.createElement('li');
                            li.textContent = pool.poolName;
                            li.style.cursor = 'pointer';
                            li.onclick = () => selectPool(pool.poolName);
                            poolList.appendChild(li);
                        });
                        
                        // 如果没有选中任何线程池，则选择第一个
                        if (!currentSelectedPool && data.resultData.length > 0) {
                            selectPool(data.resultData[0].poolName);
                        }
                        poolCountDoC.innerText=data.resultData.length+" 个线程池";
                    }
                });
        }
        
        // 获取线程池详细信息
        function getThreadPoolDetails(poolName) {
            fetch(`/lancer-thread-pool/monitor/queryDetails?poolName=${poolName}`)
                .then(response => response.json())
                .then(data => {
                    if (data.status === 1) { // 使用正确的状态码1表示成功
                        const info = data.resultData;
                        poolDetails.innerHTML = `
                            <p>核心线程数: ${info.corePoolSize}</p>
                            <p>最大线程数: ${info.maxPoolSize}</p>
                            <p>活跃线程数: ${info.activeThreads}</p>
                            <p>任务队列大小: ${info.queueCapacity}</p>
                            <p>拒绝策略: ${info.rejectText}</p>
                        `;
                        
                        // 填充表单数据
                        configForm.poolName.value = info.poolName;
                        configForm.corePoolSize.value = info.corePoolSize;
                        configForm.maxPoolSize.value = info.maxPoolSize;
                        configForm.keepAliveTime.value = info.keepAliveTime;
                        configForm.queueCapacity.value = info.queueCapacity;
                        configForm.rejectEnum.value = info.rejectEnum;
                    }
                });
        }

        // 更新线程池配置
        configForm.addEventListener('submit', function(e) {
            e.preventDefault();

            const formData = {
                poolName: configForm.poolName.value,
                corePoolSize: parseInt(configForm.corePoolSize.value),
                maxPoolSize: parseInt(configForm.maxPoolSize.value),
                keepAliveTime: parseInt(configForm.keepAliveTime.value),
                queueCapacity: parseInt(configForm.queueCapacity.value),
                rejectEnum: rejectEnumSelect.value
            };
            
            fetch('/lancer-thread-pool/monitor/buildOrUpdate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 1) {
                    showToast("配置更新成功", "success");
                    getThreadPoolList();
                    getThreadPoolDetails(currentSelectedPool);
                }
                else {
                    showToast("配置更新失败：" + (data.message || "未知错误"), "error");
                }
            });
        });
        
        // 初始化ECharts图表
        function initChart() {
            chart.setOption({
                title: {
                    text: `实时监控 - 当前: ${currentSelectedPool || '未选择'}`
                },
                tooltip: { trigger: 'axis' },
                legend: { data: ['活动线程数', '队列大小'] },
                xAxis: { type: 'category', data: [] },
                yAxis: {},
                series: [
                    { name: '活动线程数', type: 'line', data: [] },
                    { name: '队列任务数', type: 'line', data: [] }
                ]
            });
        }
        
        // 获取图表数据并更新
        function updateChartData() {
            if (!currentSelectedPool) return;
            
            fetch(`/lancer-thread-pool/monitor/queryDetails?poolName=${currentSelectedPool}`)
                .then(response => response.json())
                .then(data => {
                    if (data.status === 1) {
                        const info = data.resultData;
                        const option = chart.getOption();
                        
                        // 添加新数据点
                        const now = new Date().toLocaleTimeString();
                        option.xAxis[0].data.push(now);
                        option.series[0].data.push(info.activeThreads);
                        option.series[1].data.push(info.queueSize);
                        option.title[0].text = `当前: ${currentSelectedPool}`;
                        chart.setOption(option);
                        // 保持最多50个数据点
                        if (option.xAxis[0].data.length > 50) {
                            option.xAxis[0].data.shift();
                            option.series[0].data.shift();
                            option.series[1].data.shift();
                        }
                        
                        chart.setOption(option);
                    }
                });
        }
        
        // 页面初始化加载
        function init() {
            getRejectEnums();
            getThreadPoolList();
            initChart();
            
            // 每1秒更新一次图表数据
            setInterval(() => {
                updateChartData();
                getThreadPoolList();
            }, 1000);
        }
        
        // 页面加载完成后初始化
        window.onload = init;
    </script>
</body>
</html>